package com.sparrow.socket.tcp.codec;

import com.sparrow.socket.anno.Packet;
import com.sparrow.socket.util.CodecUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 返回游戏客户端编码器
 *
 * 长度 4字节
 * 消息id 4字节
 * 消息体内容 动态字节数量
 */
public class ResponseEncoder extends MessageToByteEncoder<Object> {

    private static final int HEAD_BYTES = 4;

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) {
        int lenIndex = out.writerIndex();
        //长度占坑位
        out.writeInt(0);

        int len = 0;
        int msgId = msg.getClass().getAnnotation(Packet.class).msgId();
        out.writeInt(msgId);
        len += 4;

        byte[] bytes = CodecUtil.encode(msg);
        out.writeBytes(bytes);
        len += bytes.length;
        out.setInt(lenIndex, len);
    }

}
